﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;

namespace HY.WinForm
{
    /// <summary>
    /// 利用using语法进行前后执行数据绑定
    /// </summary>
    public class DataGridViewBindData : IDisposable
    {
        private int[] _ColumnWidths;
        private DataGridView _View;

        public DataTable Data { get;  }
        public DataGridViewBindData(DataGridView view, Func<DataTable> dtGet)
        {
            _View = view;
            _ColumnWidths = new int[view.ColumnCount];
            for (int i = 0; i < view.Columns.Count; ++i)
                _ColumnWidths[i] = view.Columns[i].Width;

            view.DataSource = null;
            if (view.Columns.Count == 0)
                view.Columns.Add("Column1", "数据项");
            if (view.Rows.Count == 0)
                view.Rows.Add(1);
            view.Rows[0].Cells[0].Value = "正在获取...";
            Application.DoEvents();
            view.Columns.Clear();
            Data = dtGet();
        }

        void IDisposable.Dispose()
        {
            _View.DataSource = Data;
            if (_ColumnWidths.Length == _View.ColumnCount)
                for (int i = 0; i < _View.Columns.Count; ++i)
                    _View.Columns[i].Width = _ColumnWidths[i];
        }
    }
}
